package com.freejava.test_encache.service;

import com.freejava.test_encache.pojo.Cement;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@CacheConfig(cacheNames = "cement")
public class CementService {

    public List<Cement> getAll() {
        System.out.println("查询获取所有水泥数据");
        List<Cement> cements = new ArrayList<Cement>();
        // 计算时间戳
        long unixTime = System.currentTimeMillis() / 1000L;
        int nowUnixTime = (int) unixTime;
        // 创建数据
        cements.add(new Cement(1, "海螺水泥", "安徽", "160.00", nowUnixTime));
        cements.add(new Cement(2, "福建水泥", "福建", "162.00", nowUnixTime));
        cements.add(new Cement(3, "上峰水泥", "甘肃", "163.00", nowUnixTime));

        return cements;
    }

    @Cacheable(key = "#id")
    public Cement getById(int id) {
        System.out.println("想要查询id为" + id + "的水泥数据");
        // 计算时间戳
        long unixTime = System.currentTimeMillis() / 1000L;
        int nowUnixTime = (int) unixTime;
        if (id == 1) {
            return new Cement(1, "海螺水泥", "安徽", "160.00", nowUnixTime);
        } else if (id == 2) {
            return new Cement(2, "福建水泥", "福建", "162.00", nowUnixTime);
        } else if (id == 3) {
            return new Cement(3, "上峰水泥", "甘肃", "163.00", nowUnixTime);
        }
        return null;
    }

    /**
     * 更新水泥数据
     *
     * @param cement
     * @return
     */
    @CachePut(key = "#cement.id")
    public Cement updateCementById(Cement cement) {
        System.out.println("想要更新id为" + cement.getId() + "的水泥数据");
        cement.setPrice("173.00");
        return cement;
    }

    @CacheEvict(key = "#id")
    public void deleteCementById(int id) {
        // 删除一些数据
        System.out.println("删除了数据");
    }
}
